As you already know with Cloud Run, you should complete all work before
you return a request to the user, because that request might be the last
request to run on that container. So let's discuss background tasks. Here are the reasons why you should finish
all work before returning a request to the user. As soon as a container is
not handling any request for a longer than 100 milliseconds,
the CPU is throttled. Request to third party Apis might fail and Cloud Run can shut down
the container at any time. I'm returning to this topic again, because there are many valid
reasons to run a background task. Here are some example use cases. A user submits a file and your application needs to process
the file without blocking the request. Your application inserts a new record
which requires updates to a search index. The request from the user is the start
of a workflow with multiple steps that take some time to complete. As it turns out, PubSub can solve
these problems for you, and increase the reliability of your
application As a side effect. This is how you run a background
task using pumps up the pattern for cloud tasks is very similar. First, from your application
instead of executing the task using a background thread,
you publish a message to PubSub. A push subscription will forward
the message to a secondary or even the same Cloud Run service. The end point on the secondary
service actually performs the task. There are additional
benefits to this solution. Firstly, error handling
with re tries is built in. If you use a secondary Cloud Run service, it can scale independently from the
service that handles the initial request. To summarize,
Cloud Run does not have internal DNS. Use environment variables to
configure other services using URLs. You publish a message
to a PubSub topic and use push subscriptions to send
messages to any https endpoint. Messages can be delivered more than once. Record the message ID to prevent
duplicate message handling. Use cloud tasks over PubSub if you need
longer timeouts or request rate control.